package com.stxx.stiot2.controller;


import com.stxx.framwork.domain.R;
import com.stxx.framwork.domain.model.PageQuery;
import com.stxx.framwork.domain.model.PageResult;
import com.stxx.stiot2.domain.Gateway;
import com.stxx.stiot2.domain.ext.ReportData;
import com.stxx.stiot2.event.ReportListener;
import com.stxx.stiot2.event.dto.T2pMsg;
import com.stxx.stiot2.external.InfluxdbServer;
import com.stxx.stiot2.service.GatewayService;
import org.noear.solon.annotation.*;
import org.noear.solon.core.event.EventBus;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Controller
@Mapping("/iot")
public class IotController {

    @Inject
    GatewayService gatewayService;
    @Inject
    InfluxdbServer influxdbServer;

    @Post
    @Mapping("/{gatewayCode}/{terminalCode}/report")
    public R<Void> report(@Path String gatewayCode
            , @Path String terminalCode
            , @Body ReportData reportData) throws SQLException {
        Gateway r = gatewayService.queryById(gatewayCode);
        if(r == null) {
            return R.fail("没有找到网关");
        }
       T2pMsg message = new T2pMsg();
        message.setGatewayCode(gatewayCode);
        message.setTerminalCode(terminalCode);
        message.setData(reportData);
        EventBus.publish(message);
        return R.ok();
    }

    @Post
    @Mapping("/terminal/{gatewayCode}/{terminalCode}/rpc")
    public PageResult<Gateway> terminalRpc(@Path String gatewayCode
            ,@Path String terminalCode
            ,@Body Map<String,Object> params) throws SQLException {
        return null;
    }

    @Post
    @Mapping("/device/{gatewayCode}/{deviceCode}/rpc")
    public PageResult<Gateway> deviceRpc(@Path String gatewayCode
            ,@Path String terminalCode
            ,@Body Map<String,Object> params) throws SQLException {
        return null;
    }

    @Get
    @Mapping("/queryData")
    public List<Map<String,Object>> queryData(@Param String script) throws SQLException {
        return influxdbServer.query(script);
    }
}
